<template>
	<n-space style=" max-width: 1150px;">
		<n-space  v-for="item,index in extraArr">
			<n-input style="width:300px" pair separator=":" :placeholder="['key','value']"  v-model:value="extraArr[index]"  clearable />
			<n-popconfirm @positive-click="() => handleDeleteExtraRow(index)" @negative-click="() => { }">
					<template #trigger>
						<n-button strong secondary circle type="error" size="small" class="mt-1">
							<template #icon>
								<svg-icon icon="material-symbols:delete" />
							</template>
						</n-button>
					</template>
					是否确认删除当前行数据
				</n-popconfirm>
		</n-space>
		<n-button strong secondary type="primary" @click="handleAddExtraArr">添加</n-button>
	</n-space>
</template>

<script  setup lang='ts' >
import { onMounted, ref, toRefs } from 'vue';
type Props = {
	extra:Record<string,string>
}
const emit = defineEmits(["update:extra"]);
const props = defineProps<Props>()
const { extra } = toRefs(props)

const extraArr = ref<[string,string][]>([])

function init(){
	if(!extra || !extra.value){
		return ;
	}
	for(const key in extra.value){
		extraArr.value.push([key,extra.value[key]])
	}
}
function handleAddExtraArr(){
	extraArr.value.push(['',''])
}
function handleDeleteExtraRow(index:number){
	extraArr.value.splice(index,1)
}
function arr2Extra(){
	const newExtra:Record<string,string> = {}
	extraArr.value.forEach(it=>{
		if(it.length != 2 || !it[0] || !it[1]){
			window.$message?.error("扩展变量校验失败，请检查数据后，重新提交！")
			throw new Error("arr2Extra error")
		}
		newExtra[it[0]] = it[1]
	})
	emit("update:extra",newExtra)
	return newExtra;
}
defineExpose({arr2Extra})
onMounted(()=>{
	init()
})
</script>

<style lang='scss' scoped>

</style>
